<template>
  <main class="App">
    <div class="box box1">
      <div class="anim" ref="anim1Ref">
        <div class="circle" ref="circleRef"></div>
      </div>
    </div>
    <div class="box box2">
      <div class="anim">
        我是第 个动画区域
      </div>
    </div>
  </main>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";


const circleRef = ref<HTMLDivElement | null>();
const anim1Ref = ref<HTMLDivElement | null>();

function useAnimater() {
  return function (dom: HTMLDivElement, valObj: any,) {
    for (const key in valObj) {
      if (Object.prototype.hasOwnProperty.call(valObj, key)) {
        dom.style[key as any] = valObj[key];
      }
    }
  };
}
function useAnimation(scrollStart: number, scrollEnd: number, valStart: any, valEnd: any) {
  return function (scrollTop: number) {
    // 小于初始值，给初始状态
    if (scrollTop < scrollStart) return valStart;
    // 大于初始值，给结束状态
    if (scrollEnd < scrollTop) return valEnd;
    // 初始值加上递增的值，最终达到结束状态
    /**
     * valStart：初始值
     * (valEnd - valStart)：值的变化总量
     * (x - scrollStart)：已经滚动过的距离
     * (scrollEnd - scrollStart)：滚动总距离
     * (x - scrollStart) / (scrollEnd - scrollStart)设为progress：已滚动距离占总滚动距离的百分比
     * (valEnd - valStart) * progress：获取已滚动距离对应的当前值
     */
    const progress = (scrollTop - scrollStart) / (scrollEnd - scrollStart);
    // 即为最终页面上展示的值
    return valStart + (valEnd - valStart) * progress;
  };
}
const Animater = useAnimater();

onMounted(() => {
  const Animation = useAnimation(100, 200, 0, 1);
  window.addEventListener("scroll", (evt: any) => {
    const circle = circleRef.value!;
    const scrollTop = evt.target.scrollingElement.scrollTop;
    const y = Animation(scrollTop);
    Animater(circle, { transform: `scale(${y})`, opacity: y });
    console.log("scrollTop", scrollTop);
  });
});




</script>

<style scoped>
.App {
  padding-bottom: 100vh;
}

.box {
  width: 100vw;
  height: 200vh;
}

.box1 {
  background-color: lightblue;
}

.box2 {
  background-color: lightgreen;
}

.anim {
  width: 100vw;
  height: 50vh;
  background-color: orange;
  position: sticky;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.circle {
  width: 100px;
  height: 100px;
  background-color: orangered;
  opacity: 0;
  border-radius: 50%;
}
</style>
